package dy.com.第6六章简易聊天室.simpleClient.Client;

import dy.com.收发并行.constants.UDPConstants;
import dy.com.第6六章简易聊天室.simpleClient.Client.bean.ServerInfo;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class ClientTest {
    private static boolean done ;

    public static void main(String[] args) throws IOException {

        ServerInfo info = UDPClientSearcher.searchServer(UDPConstants.PORT_CLIENT_RESPONSE, 10000);
        System.out.println("Server:" + info);

        if (info == null) {
            return;
        }
        List<TCPClient2> tcpClient2s = new LinkedList<>();
        for (int i = 0; i < 100; i++) {

            try {
                TCPClient2 tcpClient = TCPClient2.startWith(info);
                if (tcpClient == null) {
                    System.out.println("连接错误");
                    continue;
                }

                tcpClient2s.add(tcpClient);
                System.out.println("连接成功: " + tcpClient2s.size());

            } catch (IOException e) {
                System.out.println("连接异常");
            }
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        while(true){
            int a =System.in.read();
            if(a==(int)'1'){
                break;
            }
        }
        System.out.println("开始runnable");
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (!done) {
                    for (TCPClient2 tcpClient2 : tcpClient2s) {
                        tcpClient2.send("Hello ");
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        //创建一个线程，用于执行所有客户端每秒发送Hello的操作
        Thread thread = new Thread(runnable);
        thread.start();
        System.out.println("写线程已经启动");
        //捕捉下一次键盘输入，停止发送

        while(true){
            int a =System.in.read();
            if(a==(int)'2'){
                break;
            }
        }
        System.out.println("收到停止信号");
        done = true;

        //等写的线程完成后关闭所有的客户端
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //退出各个客户端
        for(TCPClient2 tcpClient2:tcpClient2s){
            tcpClient2.exit();
        }
    }


}
